import { App, mall, toast, storage } from '../../../../library/api/index'

Page({
  data: {
    navMall: 'on',
    pid: '',
    products: [],
    product: {},
    tip: 'blank',
    tipData: {}
  },
  onLoad: function(e) {
    this.setData({
      pid: e.pid
    })
    App.jice.onLoad(e)
  },
  onReady: function() {
    this.get()
    App.jice.track('page', {
      pagepath: '/pages/mall/milk/view/index',
      pageTitle: '奶粉商城-查看商品详情',
      pageType: 'view'
    })
    App.logger({
      type: App.G.view,
      channel: App.G.channel,
      target: '奶粉商城-查看商品详情'
    })
  },
  onShow: function() {
    storage.get('products').then(res => {
      this.setData({
        products: res.data
      })
    })
    App.jice.track('appshow')
  },
  onHide: function() {
  },
  get: function() {
    toast.show(5000)
    mall.getProduct(this.data.pid, r => {
      toast.close()
      if(r.code == 200) {
        this.setData({
          product: r.data
        })
        this.reloadCart()
      } else {
        this.showErrorTip(r.data)
      }
    }, r => {
      this.showErrorTip(r.data)
    })
  },
  addCart: function(e) {
    var pid = e.currentTarget.dataset.pid
    storage.get('cart_milk_items').then(items => {
      if(!items) {
        items = []
        items.push(pid)
      } else {
        let isAdded = false
        for(let i = 0; i < items.length; i++) {
          if(items[i] == pid) {
            isAdded = true
            break
          }
        }
        if(!isAdded) {
          items.push(pid)
        }
      }
      storage.set('cart_milk_items', items).then(() => {
        this.reloadCart()
      })
    })
  },
  removeCart: function(e) {
    var pid = e.currentTarget.dataset.pid
    storage.get('cart_milk_items').then(items => {
      if(items) {
        for(let i = 0; i < items.length; i++) {
          if(items[i] == pid) {
            items.splice(i, 1)
            break
          }
        }
      }
      storage.set('cart_milk_items', items).then(() => {
        this.reloadCart()
      })
    })
  },
  reloadCart: function() {
    storage.get('cart_milk_items').then(items => {
      this.data.product['is_add'] = false
      for(let n = 0; n < items.length; n++) {
        if(items[n] == this.data.pid) {
          this.data.product['is_add'] = true
        }
      }
      this.setData({
        product: this.data.product
      })
    })
  },
  showErrorTip: function(message) {
    this.setData({
      tip: 'error_tip',
      tipData: message
    })
  },
  closeTip: function() {
    this.setData({
      tip: 'blank',
      tipData: {}
    })
  }
})